package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.exception.MyException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService{

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 添加预约设置
     * @param orderSettingList
     */
    @Override
    @Transactional
    public void add(List<OrderSetting> orderSettingList) {

        //首先遍历预约设置表单，进行非空判断
        if (null != orderSettingList){

            for (OrderSetting orderSetting : orderSettingList) {

            //通过日期查询预约设置表
            OrderSetting osInDB =  orderSettingDao.findByOrderDate(orderSetting.getOrderDate());

            //如果存在预约设置,进行非空判断
             if (null != osInDB){
                 //先判断更新后的最大数是否小于已预约人数
                 if (orderSetting.getNumber() < osInDB.getReservations()){

                     //如果小于预约人数，则报错，并提示已预约数超过最大预约数，接口异常声明
                     throw new MyException("更新后的最大预约数，不能小于已预约数");
                 }
                 //或者，则可以更新最大预约数
                 orderSettingDao.updateNumber(orderSetting);
             }else {
                 //否则不存在的话，则添加预约设置
                 orderSettingDao.add(orderSetting);
             }
            }
        }
    }

    /**
     * 通过月份查询预约设置
     * @param mouth
     * @return
     */
    @Override
    public List<Map<String, Integer>> getDataByMonth(String mouth) {

        //拼接月份,month = month + "%",拼接%,就是"2020-11%"，模糊查找
        //%是占位符，就是查找这个2019-11开头的数据，2020-11后面可以接任何数据 都可以匹配
        mouth+="%";

        return orderSettingDao.getDataByMonth(mouth);
    }

    /**
     * 基于日历的预约设置
     * @param orderSetting
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //通过日期查询预约设置表
        OrderSetting byOrderDate = orderSettingDao.findByOrderDate(orderSetting.getOrderDate());

        //进行非空判断，判断如果存在预约设置
        if (null != byOrderDate){

            //判断更新后的预约大数是否小于已预约人数
            if (orderSetting.getNumber() < byOrderDate.getReservations()){

               //小于，报错 已预约数超过最大预约数，接口异常声明
               throw  new MyException("更新后的最大预约数，不能小于已预约数");

            }
           //大于，则可以更新最大预约数
           orderSettingDao.updateNumber(orderSetting);
        }else {

            //否则不存在的话，则直接添加预约设置
            orderSettingDao.add(orderSetting);
        }
    }
}
